﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmartMD.DataModel.Entity;
using System.Data;

namespace SmartMD.DataAccess.Oracle.DaoImpl
{
    public class DictionaryItemDaoImpl : BaseGenericDaoImpl
    {
        public bool saveDictItems(List<DictionaryItem> dictItems)
        {
            bool isSaved = true;
            DictionaryItem dictItem;
            //
            string deleteSql = "delete from DUO_DIC_INFO where DICTYPEID = '" + dictItems[0].DictTypeId + "'";
            this.dbConn.Delete(deleteSql);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < dictItems.Count; i++)
            {
                dictItem = dictItems[i];
  
                sb.Clear();
                sb.Append(" insert into");
                sb.Append(" DUO_DIC_INFO (DICTID, DICTYPEID, NAME, CODE, FATHERID, ORDERNO, ISVALID, CREATEDATE)");
                sb.Append(" values(");
                sb.Append(" '" + dictItem.Id + "',");
                sb.Append(" '" + dictItem.DictTypeId + "',");
                sb.Append(" '" + dictItem.Name + "',");
                sb.Append(" '" + dictItem.Code + "',");
                sb.Append(" '" + dictItem.ParentId + "',");
                sb.Append(" '" + dictItem.Order + "',");
                sb.Append(" '" + dictItem.IsValid + "',");
                sb.Append(" to_date ('" + dictItem.CreateDate.ToString("yyyy-MM-dd HH:mm:ss") + "' , 'YYYY-MM-DD HH24:MI:SS' )"); 
               
                sb.Append(")");
               isSaved = this.dbConn.Insert(sb.ToString());
            }
            return isSaved;
        }

        internal List<DictionaryItem> loadDictItemById(string dictTypeId)
        {
            List<DictionaryItem> dictItemList = new List<DictionaryItem>();
            DictionaryItem dictItem;
            StringBuilder sb = new StringBuilder();
            sb.Clear();
            sb.Append(" select *");
            sb.Append(" from DUO_DIC_INFO");
            sb.Append(" where DICTYPEID = '" + dictTypeId + "'");

            DataTable dt = this.dbConn.Select(sb.ToString());
            if (dt != null)
            {
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    dictItem = new DictionaryItem();
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        string clmName;
                        clmName = dt.Columns[i].ColumnName;
                        dictItem.setValue(clmName, dt.Rows[j][clmName]);
                    }

                    dictItemList.Add(dictItem);
                }
                return dictItemList;
            }            
            return null;
        }
    }
}
